package tgc.edu.tms.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.tms.custom.AjaxResult;
import tgc.edu.tms.custom.CommonController;
import tgc.edu.tms.custom.ExportExcel;
import tgc.edu.tms.custom.ImportExcel;
import tgc.edu.tms.entity.CourseCategory;
import tgc.edu.tms.entity.Curriculum;
import tgc.edu.tms.entity.Profession;
import tgc.edu.tms.entity.kcb;
import tgc.edu.tms.service.CourseCategoryService;
import tgc.edu.tms.service.CurriculumService;
import tgc.edu.tms.service.KcbService;
import tgc.edu.tms.service.ProfessionService;
import tgc.edu.tms.web.form.CurriculumForm;

@Controller
@RequestMapping(value = "/curriculum")
public class CurriculumController extends CommonController<Curriculum, Integer, CurriculumForm> {
	@Autowired
	private CurriculumService curriculumService;

	@Autowired
	private ProfessionService professionService;

	@Autowired
	private CourseCategoryService courseCategoryService;

	@Autowired
	private KcbService kcbService;

	@Override
	public void manage(ModelMap map) {
		List<String> years = professionService.findAllYear();
		if (years.size() == 0) {
			years = null;
		}
		map.put("years", years);
	}

	@Override
	public void edit(CurriculumForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		Integer id = form.getId();
		Curriculum model = new Curriculum();
		model = null;
		if (id != null) {
			model = curriculumService.findById(id);
		}
		List<String> years = professionService.findAllYear();
		if (years.size() == 0) {
			years = null;
		}
		List<CourseCategory> courseCategorys = courseCategoryService.findAll();
		map.put("years", years);
		map.put("courseCategorys", courseCategorys);
		map.put("model", model);
		if (model != null) {
			map.put("lbs", model.getLbs());
		}
	}

	@RequestMapping("/getKc")
	@ResponseBody
	public List<kcb> getKc() {
		List<kcb> kc = kcbService.findAll();
		return kc;
	}

	@Override
	public Object save(CurriculumForm form) {
		try {
			Curriculum model = new Curriculum();
			Integer id = form.getId();
			if (id != null) {
				model = curriculumService.findById(id);
			} else {
				Profession profession = professionService.findByYearAndCollegeAndProfesion(form.getYear(),
						form.getCollege(), form.getProfesion()); // 根据form对应的专业中字段查找出专业信息
				if (curriculumService.findByKcmcAndKkxqAndProfession(form.getKcmc(), form.getKkxq(),
						profession) != null) {
					return new AjaxResult(false, "数据已存在");
				}

			}
			BeanUtils.copyProperties(form, model, "id");
			model.getKclbs().clear(); // 清空原有类型
			for (int i = 0; i < form.getKclb().size(); i++) { // 取出form中各类型赋值给model
				CourseCategory category = courseCategoryService.findById(form.getKclb().get(i));
				model.getKclbs().add(category);
			}
			Profession profession = professionService.findByYearAndCollegeAndProfesion(form.getYear(),
					form.getCollege(), form.getProfesion()); // 根据form对应的专业中字段查找出专业信息
			model.setProfession(profession);
			curriculumService.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}

	@Override
	public Specification<Curriculum> buildSpec(CurriculumForm form) {
		Specification<Curriculum> spec = new Specification<Curriculum>() {

			@Override
			public Predicate toPredicate(Root<Curriculum> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				List<Predicate> rules = new ArrayList<>();
				if (StringUtils.hasText(form.getYear())) {
					rules.add(criteriaBuilder.like(root.get("profession").get("year"), "%" + form.getYear() + "%"));
				}
				if (StringUtils.hasText(form.getCollege())) {
					rules.add(
							criteriaBuilder.like(root.get("profession").get("college"), "%" + form.getCollege() + "%"));
				}
				if (StringUtils.hasText(form.getProfesion())) {
					rules.add(criteriaBuilder.like(root.get("profession").get("profesion"),
							"%" + form.getProfesion() + "%"));
				}
				if (StringUtils.hasText(form.getKkxq())) {
					rules.add(criteriaBuilder.equal(root.get("kkxq"), form.getKkxq()));
				}
				if (StringUtils.hasText(form.getSearch())) {
					Predicate like = criteriaBuilder.like(root.get("kcmc"), "%" + form.getSearch() + "%");
					Predicate like2 = criteriaBuilder.like(root.get("kcdm"), "%" + form.getSearch() + "%");
					Predicate or = criteriaBuilder.or(like, like2);
					rules.add(or);
				}
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	/*	*//**
			 * 获取年级
			 * 
			 * @param year
			 * @return
			 *//*
				 * @RequestMapping(value = "/getYear", method = RequestMethod.POST)
				 * 
				 * @ResponseBody public Object getYear(String year) { return
				 * professionService.findAllYear(); }
				 */

	/**
	 * 根据年级获取学院
	 * 
	 * @param year
	 * @return
	 */
	@RequestMapping(value = "/getCollege", method = RequestMethod.POST)
	@ResponseBody
	public Object getCollege(String year) {
		return professionService.findCollegeByYear(year);
	}

	/**
	 * 根据年级和学院获取专业
	 * 
	 * @param year
	 * @param college
	 * @return
	 */
	@RequestMapping(value = "/getProfesion", method = RequestMethod.POST)
	@ResponseBody
	public Object getProfesion(String year, String college) {
		return professionService.findProfessionByYearAndCollege(college, year);
	}

	/**
	 * 导出人才方案
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/export")
	@ResponseBody
	public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Curriculum> findAll = curriculumService.findAll();
		String title = "人才方案";
		String[] curricuName = new String[] { "序号", "课程名称", "课程代码", "总学分", "学分", "讲授学时", "实验学时", "上机学时", "其他学时", "课程类别",
				"每周学时", "考核方式", "开课学期", "年级", "学院", "专业" };
		List<Object[]> dataList = new ArrayList<Object[]>();
		for (Curriculum c : findAll) {
			String kcmc = c.getKcmc();// 课程名称
			String kcdm = c.getKcdm();// 课程代码
			Integer zongxs = c.getZongxs();// 总学分
			float xf = c.getXf();// 学分
			Integer jsxs = c.getJsxs() == null ? 0 : c.getJsxs();// 讲授学时
			Integer syxs = c.getSyxs() == null ? 0 : c.getSyxs();// 实验学时
			Integer sjxs = c.getSjxs() == null ? 0 : c.getSjxs();// 上机学时
			Integer qtxs = c.getQtxs() == null ? 0 : c.getQtxs();// 其他学时
			String kclb = c.getKclb() == null ? "-" : c.getKclb();// 课程类别
			Integer zhouxs = c.getZhouxs() == null ? 0 : c.getZhouxs();// 每周学时
			String khfs = c.getKhfs();// 考核方式
			String kkxq = c.getKkxq();// 开课学期
			String year = c.getYear();// 年级
			String college = c.getCollege();// 学院
			String profesion = c.getProfesion();// 专业
			Object[] objs = { kcmc, kcmc, kcdm, zongxs, xf, jsxs, syxs, sjxs, qtxs, kclb, zhouxs, khfs, kkxq, year,
					college, profesion };

			dataList.add(objs);
		}
		// 实例化工具类
		ExportExcel ex = new ExportExcel(title, curricuName, dataList, request, response);
		try {
			// 导出excel
			ex.export();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 人才方案导入
	 */
	@RequestMapping(value = "/excelimport")
	@ResponseBody
	public Object excelimport(MultipartFile file) throws IOException {
		try {
			// 实例化工具类
			ImportExcel excelReader = new ImportExcel();
			InputStream is = file.getInputStream();
			// 导入excel
			excelReader.readExcelContent(is);
			Map<Integer, String> map = excelReader.readExcelContent(is);
			is.close();
			// 这里由于xls合并了单元格需要对索引特殊处理
			for (int i = 3; i <= map.size() + 1; i++) {
				String[] scoreArray = map.get(i).split("-");
				System.out.println(map.get(i));

				String year = scoreArray[1];
				String college = scoreArray[2];
				String profesions = scoreArray[3];
				String kcmc = scoreArray[4];
				String kcdm = scoreArray[5];
				String zongxs = scoreArray[6];
				String xf = scoreArray[7];
				String jsxs = scoreArray[8];
				String syxs = scoreArray[9];
				String sjxs = scoreArray[10];
				String qtxs = scoreArray[11];
				String kclb = scoreArray[12];
				String zhouxs = scoreArray[13];
				String khfs = scoreArray[14];
				String kkxq = scoreArray[15];
				List<Profession> years = professionService.findYear(year);
				if (years == null) {
					return "第" + (i + 1) + "年级数据未找到,请检查!";
				}
				List<Profession> findByCollegeAndYear = professionService.findByCollegeAndYear(college, year);
				if (findByCollegeAndYear == null) {
					return "第" + (i + 1) + "学院数据未找到,请检查!";
				}
				Profession findByyearAndprofesion = professionService.findByyearAndprofesion(year, profesions);
				if (findByyearAndprofesion == null) {
					return "第" + (i + 1) + "专业数据未找到,请检查!";
				}

				Profession profession = professionService.findByYearAndCollegeAndProfesion(year, college, profesions); // 根据excel对应的专业中字段查找出专业信息
				if (curriculumService.findByKcmcAndKkxqAndProfession(kcmc, kkxq, profession) != null) {
					return new AjaxResult(false, "数据已存在");
				}

				Curriculum model = new Curriculum();
				model.setProfession(findByyearAndprofesion);
				model.setKcmc(kcmc);
				model.setKcdm(kcdm);
				model.setZongxs(Integer.parseInt(zongxs));
				model.setXf(Float.parseFloat(xf));
				model.setJsxs(Integer.parseInt(jsxs));
				model.setSyxs(Integer.parseInt(syxs));
				model.setSjxs(Integer.parseInt(sjxs));
				model.setQtxs(Integer.parseInt(qtxs));
				String[] split = kclb.split("\\/");
				List<CourseCategory> list = courseCategoryService.findtypeortype(split[0], split[1]);
				model.setZhouxs(Integer.parseInt(zhouxs));
				model.setKhfs(khfs);
				model.setKkxq(kkxq);
				model.setKclbs(list);
				curriculumService.save(model);
			}
			return "数据保存成功";
		} catch (Exception e) {
			return "数据保存失败";
		}

	}
}
